<?php
/**
 * Created by PhpStorm.
 * User: zhixuedong
 * Date: 2022/3/29
 * Time: 15:08
 */

namespace app\api\controller;

use app\project\service\PublicService;
use think\Config;
use think\Controller;
use think\Db;
use think\Exception;
use think\Session;
use think\Validate;
class Expose extends Controller
{

    //批量更新推进计划数据
//    public function beachUpdate(){
//        $where['id'] = ['gt',0];
//        $list  = Db::name("project_pro_advance")->where($where)->select();
//        foreach ($list as $k=>$v){
//            $typeWhere['id'] = $v['sub_id'];
//            $typeDetail = Db::name("project_type")->where($typeWhere)->find();
//            if($typeDetail['type']==8){
//                $update['plan_category'] = 2;
//            }else{
//                $update['plan_category'] = 1;
//            }
//            Db::name("project_pro_advance")->where(['id'=>$v['id']])->update($update);
//        }
//    }

    //查询项目基本信息
    public function projectDetail(){
        $common = new Common();
        if(!empty($_POST['uid'])){
            $project_user = $common->testusername($_POST['uid']);
        }else{
            $project_user = $this->iflogin();
        }

        try{
            $where['id'] = $_POST['id'];
            $detail = Db::name("project_pro")->field("id,title,leader,duty_unit,progress,year_progress,project_type,lng,lat,library,menuTop,enterprise,project_chief")->where($where)->find();
            $pro_type = config("pro_type");

            unset($where);
            $where['id'] = $detail['project_type'];
            $typeDetail = Db::name("project_type")->where($where)->find();
            if(!empty($typeDetail)){
                $detail['project_type'] = $typeDetail['name'];
            }
            unset($where);
            $where['id'] = $detail['enterprise'];
            $typeDetail = Db::name("project_type")->where($where)->find();
            if(!empty($typeDetail)){
                $detail['enterprise'] = $typeDetail['name'];
            }
            $detail['menuTop'] = empty($pro_type[$detail['menuTop']])?"":$pro_type[$detail['menuTop']];

            //已关联项目
            $proWhere['account_id'] = $project_user['id'];
            $project_id = Db::name("project_account_pro")->where($proWhere)->field("project_id")->select();
            if(!empty($project_id)){
                $project_id = array_column($project_id,'project_id');
            }
            //已关联项目end

            $auto = in_array($detail['id'],$project_id);
            $detail['auto'] = empty($auto)?0:1;

            $black['detail'] = $detail;
            $black['code'] = 0;
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }

    //查询重点项目与企业
    public function projectList(){
        $common = new Common();
        if(!empty($_POST['uid'])){
            $project_user = $common->testusername($_POST['uid']);
        }else{
            $project_user = $this->iflogin();
        }
        try{
            if(!empty($_POST['keyword'])){
                $where['title'] = ['like',"%{$_POST['keyword']}%"];
            }

            $where['library'] = ['in',[3,4,6]];
            $where['lng'] = ['neq',''];
            $where['lat'] = ['neq',''];
            $list = Db::name("project_pro")->field("id,title,lng as longitude,lat as latitude,library")->where($where)->select();
            $pro_type = config("pro_type");
            foreach ($list as $k=>$v){
//                unset($where);
//                $where['id'] = $v['project_type'];
//                $typeDetail = Db::name("project_type")->where($where)->find();
//                if(!empty($typeDetail)){
//                    $list[$k]['project_type'] = $typeDetail['name'];
//                }
//                unset($where);
//                $where['id'] = $v['enterprise'];
//                $typeDetail = Db::name("project_type")->where($where)->find();
//                if(!empty($typeDetail)){
//                    $list[$k]['enterprise'] = $typeDetail['name'];
//                }
//                $list[$k]['menuTop'] = empty($pro_type[$v['menuTop']])?"":$pro_type[$v['menuTop']];
                $list[$k]['width'] = 30;
                $list[$k]['height'] = 30;
                $iconPath = ($v['library']==6)?"/images/qy.png":"/images/xm.png";
                $list[$k]['iconPath'] = $iconPath;
            }

            $black['list'] = $list;
            $black['code'] = 0;
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }


    //查询招商库逾期签约项目
    public function ListApi(){
        $common = new Common();
        if(!empty($_POST['uid'])){
            $project_user = $common->testusername($_POST['uid']);
        }else{
            $project_user = $this->iflogin();
        }
        try{
            $oldTime = strtotime("-1 month");
            $year = date("Y",$oldTime);
            $month = date("m",$oldTime);

            //判断是否有点评权限
            $commentAuto = Db::name("project_account")->where(['id'=>$project_user['id']])->value("comment");
            $page = empty($_POST['page'])?1:intval($_POST['page']);
            $limit = empty($_POST['limit'])?100:intval($_POST['limit']);
//            $limit = 100;
            $start = ($page - 1) * $limit;

            //已关联项目
            $proWhere['account_id'] = $project_user['id'];
            $project_id = Db::name("project_account_pro")->where($proWhere)->field("project_id")->select();

            if(!empty($project_id)){
                $project_id = array_column($project_id,'project_id');
                $project_ids = implode($project_id,",");
            }

            if(empty($project_ids)){
                $project_ids = 0;
            }
            //已关联项目end

            $where = "1=1";

            //筛选
            if(!empty($_POST['comment'])){
                $where .=" and comment=".$_POST['comment'];
            }
            if(!empty($_POST['project_type'])){
                $where .=" and project_type=".$_POST['project_type'];
            }
            if(!empty($_POST['progress'])){
                $progress = $_POST['progress'];
                $nowtime = date('Y-m-d',time());
                if($progress==1){
                    $where .=" and plan_complete_time>='$nowtime'";
                }else{
                    $where .=" and plan_complete_time<'$nowtime'";
                }
            }

            if(!empty($_POST['complete'])){
                $complete = $_POST['complete'];
                if($complete==1){
                    $where .=" and progress=100 and project_status=0";
                }else{
                    $where .=" and progress<100 and project_status=0";
                }
            }

            if(!empty($_POST['keyword'])){
                $where .=" and (title like '%".$_POST['keyword']."%' or duty_unit like '%".$_POST['keyword']."%' or duty_person like '%".$_POST['keyword']."%') ";
            }

            if(!empty($_POST['myname'])){
                $where .=" and (duty_person like '%".$project_user['name']."%' or leader like '%".$project_user['name']."%')";
            }

            $order = "sort desc,id desc";

            if(!empty($_POST['library'])){
                $where .=" and library =".$_POST['library'];
                switch ($_POST['library']){
                    case 1:
                        if(!empty($_POST['sign'])){
                            $sign = $_POST['sign'];
                            $where .=" and sign=".$sign;
                        }
                        break;
                    case 2:

                        //曝光台条件
//                        $addWhere = "a.year=$year and a.month=$month and a.declare_status in(0,2) and b.library=2 and b.start_status!=4 and a.is_del=0";
//                        $listIds = Db::name("project_pro_advance as a")
//                            ->join("project_pro b","a.pro_id = b.id and a.plan_category=b.plan_category")->where($addWhere)
//                            ->field("b.id")
//                            ->group("a.pro_id")->select();
                        $addWhere['color'] = 2;
                        $listIds = Db::name("project_pro_advance_plan")->field("pro_id")->where($addWhere)->group("pro_id")->select();


                        $listIds = array_column($listIds,"pro_id");
                        $listIds = implode($listIds,",");
                        $listIds = empty($listIds)?0:$listIds;
                        $where .=" and (id in($listIds) or pid in ($listIds)) and start_status!=2";


                        if(!empty($_POST['start_status'])){
                            $start_status = $_POST['start_status'];
                            $where .=" and start_status=".$start_status;
                        }

                        if(!empty($_POST['invest_type'])){
                            $invest_type = $_POST['invest_type'];
                            $where .=" and invest_type=".$invest_type;
                        }
                        break;
                    case 3:

                        //曝光台条件
//                        $addWhere = "a.year=$year and a.month=$month and a.declare_status in(0,2) and b.library=3 and b.project_status!=3 and a.is_del=0";
//                        $listIds = Db::name("project_pro_advance as a")
//                            ->join("project_pro b","a.pro_id = b.id and a.plan_category=b.plan_category")->where($addWhere)
//                            ->field("b.id")
//                            ->group("a.pro_id")->select();
                        $addWhere['color'] = 2;
                        $listIds = Db::name("project_pro_advance_plan")->field("pro_id")->where($addWhere)->group("pro_id")->select();


                        $listIds = array_column($listIds,"pro_id");
                        $listIds = implode($listIds,",");
                        $listIds = empty($listIds)?0:$listIds;
                        $where .=" and (id in($listIds) or pid in ($listIds))";

                        if(!empty($_POST['warehousing'])){
                            $warehousing = $_POST['warehousing'];
                            $where .=" and warehousing=".$warehousing;
                        }
                        if(!empty($_POST['project_status'])){
                            $project_status = $_POST['project_status']-1;
                            $where .=" and project_status=".$project_status;
                        }
                        if(!empty($_POST['invest_type'])){
                            $invest_type = $_POST['invest_type'];
                            $where .=" and invest_type=".$invest_type;
                        }
                        break;
                    case 4:
//                        $addWhere = "a.year=$year and a.month=$month and a.declare_status in(0,2) and b.library=4 and b.project_status!=3 and a.is_del=0";
//                        $listIds = Db::name("project_pro_advance as a")
//                            ->join("project_pro b","a.pro_id = b.id and a.plan_category=b.plan_category")->where($addWhere)
//                            ->field("b.*")
//                            ->group("a.pro_id")->select();
                        $addWhere['color'] = 2;
                        $listIds = Db::name("project_pro_advance_plan")->field("pro_id")->where($addWhere)->group("pro_id")->select();


                        $listIds = array_column($listIds,"pro_id");
                        $listIds = implode($listIds,",");
                        $listIds = empty($listIds)?0:$listIds;
                        $where .=" and (id in($listIds) or pid in ($listIds))";

                        if(!empty($_POST['project_status'])){
                            $project_status = $_POST['project_status']-1;
                            $where .=" and project_status=".$project_status;
                        }
                        break;
                    case 5:
                        if(!empty($_POST['reply'])){
                            $reply = $_POST['reply'];
                            $where .=" and reply=".$reply;
                        }
                        break;
                    case 6:
                        $addWhere['type'] = 1;
                        $month = date("Y-m",strtotime("-1 month"));
//                        $addWhere['addtime'] = ['like',"%{$month}%"];
                        $addWhere['show_time'] = ['like',"%{$month}%"];
                        $figure = Db::name("project_pro_figure")->where($addWhere)->field("pro_id")->group("pro_id")->select();
                        $pro_id = array_column($figure,"pro_id");
                        $pro_id = implode(",",$pro_id);
                        unset($addWhere);
                        $addWhere = "library=6 and id not in($pro_id) and menuTop = 2";
                        $listIds = PublicService::ListService("project_pro",$addWhere);
                        $listIds = array_column($listIds,"id");
                        $listIds = implode($listIds,",");
                        $listIds = empty($listIds)?0:$listIds;
                        $where .=" and id in($listIds)   and condition_val!=4";

                        if(!empty($_POST['operation'])){
                            $reply = $_POST['operation'];
                            $where .=" and operation=".$reply;
                        }

                        if(!empty($_POST['cultivation'])){
                            $cultivation = $_POST['cultivation'];
                            $where .=" and cultivation=".$cultivation;
                        }

                        if(!empty($_POST['enterprise'])){
                            $enterprise = $_POST['enterprise'];
                            $where .=" and enterprise=".$enterprise;
                        }

                        if(!empty($_POST['condition_val'])){
                            $condition_val = $_POST['condition_val'];
                            $where .=" and condition_val=".$condition_val;
                        }
                        $order = "visit_time desc,sort desc,id desc";
                        break;
                }
            }
            $list = Db::name("project_pro")->where($where)
                ->field("id,title,thumb,duty_person,leader,progress,year_progress,duty_unit,project_status,difficulty,sign,start_status,warehousing,reply,liaison,operation,signTime,warehousingtitle,plan_onstream_time")
                ->limit($start,$limit)
                ->order($order)->select();
            foreach ($list as $k=>$v){
                $list[$k]['difficulty'] = empty($v['difficulty'])?'':$v['difficulty'];
                $list[$k]['content'] = empty($v['difficulty'])?'':$v['difficulty'];
                $list[$k]['leading_cadre'] = 0;
                $list[$k]['comment'] = 0;
                $list[$k]['read'] = 0;
                $list[$k]['thumb'] = empty($v['thumb'])?'':$v['thumb'];
                if(in_array($v['id'],$project_id) & $commentAuto==1){
                    //判断是否已点评
                    $commentWhere['pro_id'] = $v['id'];
                    $commentWhere['add_id'] = $project_user['id'];
                    $comment = Db::name("project_pro_comment")->where($commentWhere)->value("id");
                    $list[$k]['comment'] = empty($comment)?1:2;
                }
                if(strpos($v['duty_person'],$project_user['name'])!==false){
                    //是否存在点评信息
                    $commentCount = Db::name("project_pro_comment")->where(['pro_id'=>$v['id']])->count("id");
                    //已读数
                    $readCount = Db::name("project_pro_comment_log")->where(['pro_id'=>$v['id'],'read_id'=>$project_user['id']])->count("id");
                    //是否存在未读信息
                    if($commentCount!=0){
                        $list[$k]['read'] = ($commentCount!=$readCount)?1:2;
                    }
                    $list[$k]['leading_cadre'] = 1;
                }

                if($v['sign']==3 && !empty($v['signTime'])){
                    $TwoDays = $this->diffBetweenTwoDays($v['signTime'],date("Y-m-d"));
                    if($TwoDays>0){
                        $list[$k]['signStatus'] = 1;
                    }
                    if($TwoDays>61){
                        $list[$k]['signStatus'] = 2;
                    }
                    $list[$k]['TwoDays'] = $TwoDays;
                }


                //统计本月走访次数  progress
                $figureWhere['pro_id'] = $v['id'];
                $figureWhere['type'] = 1;
                $figureWhere['show_time'] = ['like',"%".date("Y-m")."%"];
                $list[$k]['visit_progress'] =  Db::name("project_pro_figure")->where($figureWhere)->count("*");
                //统计本年走访次数
                $figureWhere['show_time'] = ['like',"%".date("Y")."%"];
                $list[$k]['visit_year_progress'] =  Db::name("project_pro_figure")->where($figureWhere)->count("*");

            }
            $count = Db::name("project_pro")->where($where)->count("*");
            $black['code'] = 0;
            $black['msg'] = "查询成功";
            $black['list'] = $list;
            $black['count'] = $count;
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }


    //计算相差天数
    function diffBetweenTwoDays ($day1, $day2)
    {
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);
        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        return ($second1 - $second2) / 86400;
    }

    //曝光台数据
    /**
     *
    $where = "library = 1 and sign =3";
    if(!empty($_POST['keyword'])){
    $where .=" and (title like '%".$_POST['keyword']."%' or duty_unit like '%".$_POST['keyword']."%' or duty_person like '%".$_POST['keyword']."%') ";
    }
     * @return string
     *  1、招商库内逾期签约的项目个数，点进去后是列表
        2、预备库内逾期开工的项目个数，点进去后是列表
        3、开工库和重点库内的推进计划本月是逾期的项目个数，点进去后是列表
        4、双千库内本月未走访的企业个数，点进去后是列表
        5、服务直通车内已逾期的问题，点进去就是问题列表
     */
    public function index(){
        $common = new Common();
        if(!empty($_POST['uid'])){
            $project_user = $common->testusername($_POST['uid']);
        }else{
            $project_user = $this->iflogin();
        }
        try{
            //逾期签约项目数(招商库)
            $where = "library = 1 and sign =3";
            $libraryOne = PublicService::counService("project_pro",$where);

            //预备库曝光
            unset($where);
            //当前年
            $oldTime = strtotime("-1 month");
            $year = date("Y",$oldTime);
            $month = date("m",$oldTime);
//            $where = "a.year=$year and a.month=$month and a.declare_status in(0,2) and b.library=2 and b.start_status!=4 and a.is_del=0";
//            $libraryTwo = Db::name("project_pro_advance as a")
//            ->join("project_pro b","a.pro_id = b.id and a.plan_category=b.plan_category")
//            ->where($where)
//            ->field("b.*")
//            ->group("a.pro_id")->count("*");

//            $where['a.color'] = 2;
//            $where['b.library'] = 2;
//            $libraryTwo = Db::name("project_pro_advance_plan")->alias("a")
//                ->join("project_pro b","a.pro_id = b.id")
//                ->where($where) ->field("b.*")
//                ->group("a.pro_id")->count("*");
            $where['color'] = 2;
            $list = Db::name("project_pro_advance_plan")->field("pro_id")->where($where)->group("pro_id")->select();
            $listIds = array_column($list,"pro_id");

            // and a.plan_category=b.plan_category
            $overdueWhere['library'] = 2;
            $overdueWhere['id|pid'] = ['in',$listIds];
            $overdueWhere['start_status'] = ['neq',2];
            $libraryTwo = Db::name("project_pro")->field("id")->where($overdueWhere)->count('*');
            unset($overdueWhere);
            //在建库曝光
//            $where = "a.year=$year and a.month=$month and a.declare_status in(0,2) and b.library=3 and b.project_status!=3 and a.is_del=0";
//            $libraryThree = Db::name("project_pro_advance as a")
//                ->join("project_pro b","a.pro_id = b.id and a.plan_category=b.plan_category")->where($where)
//                ->field("b.*")
//                ->group("a.pro_id")->count("*");

            $overdueWhere['library'] = 3;
            $overdueWhere['id|pid'] = ['in',$listIds];
            $libraryThree = Db::name("project_pro")->field("id")->where($overdueWhere)->count('*');
            unset($overdueWhere);
            //重点库曝光
//            $where = "a.year=$year and a.month=$month and a.declare_status in(0,2) and b.library=4 and b.project_status!=3 and a.is_del=0";
//            $libraryFour = Db::name("project_pro_advance as a")
//                ->join("project_pro b","a.pro_id = b.id and a.plan_category=b.plan_category")->where($where)
//                ->field("b.*")
//                ->group("a.pro_id")->count("*");
            $overdueWhere['library'] = 4;
            $overdueWhere['id|pid'] = ['in',$listIds];
            $libraryFour = Db::name("project_pro")->field("id")->where($overdueWhere)->count('*');

            unset($where);
            //双千库曝光
            //本月走访企业
            $where['type'] = 1;
            $month = date("Y-m",strtotime("-1 month"));
//            $where['addtime'] = ['like',"%{$month}%"];
            $where['show_time'] = ['like',"%{$month}%"];
            $figure = Db::name("project_pro_figure")->where($where)->field("pro_id")->group("pro_id")->select();
            $pro_id = array_column($figure,"pro_id");
            $pro_id = implode(",",$pro_id);
            unset($where);
            $where = "library=6 and id not in($pro_id) and condition_val!=4 and menuTop=2";
            $libraryFive = PublicService::counService("project_pro",$where);

            unset($where);
            //服务直通车曝光
            $where = "pid = 0 and status = 6";
            $librarySix = PublicService::counService("project_help",$where);

            $black["libraryOne"] = $libraryOne;
            $black["libraryTwo"] = $libraryTwo;
            $black["libraryThree"] = $libraryThree;
            $black["libraryFour"] = $libraryFour;
            $black["libraryFive"] = $libraryFive;
            $black["librarySix"] = $librarySix;
            $black['code'] = 0;
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }

    public function iflogin(){
        $project_user = Session::get("project_user");
        if(empty($project_user)){
            $black['code'] = 1;
            $black['msg'] = "请重新登录";
            echo json_encode($black);die;
        }
        return $project_user;
    }


}